package com.qf.smsplatform.monitor.job;


import com.netflix.discovery.converters.Auto;
import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.RabbitMQConstants;
import com.qf.smsplatform.monitor.client.CacheService;
import com.qf.smsplatform.monitor.util.JavaMailUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.Set;

@Component
@Slf4j
public class MonitorQueueMessageJob implements SimpleJob {

    @Autowired
    private ConnectionFactory factory;

    @Resource
    private CacheService cacheService;

    @Autowired
    private JavaMailUtil javaMailUtil;

    @Override
    public void execute(ShardingContext shardingContext) {
        // 监听MQ中的队列
        // Producer - Connection - Channel(创建队列,创建交换机,发送消息)
        Connection connection = factory.createConnection();
        Channel channel = connection.createChannel(false);
        // 查询到现在所拥有的全部通道信息.
        Set<String> channelIds = cacheService.smembers(CacheConstants.CACHE_PREFIX_SMS_CHANNEL_ALL);
        // 遍历channelIds
        for (String channelId : channelIds){
            // 声明队列名称
            String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + channelId;

            // 创建队列(如果队列存在， 不用管)
            try {
                channel.queueDeclare(queueName,true,false,false,null);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 获取队列中的消息数量
            int messageCount = 0;
            try {
                messageCount = channel.queueDeclarePassive(queueName).getMessageCount();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 判断消息数量
            if(messageCount > 10000){
                // 给运维人员/开发人员发送邮件，通知消息堆积。。。。
                log.info("【监控模块】 {}队列中的消息，出现了消息堆积，消息的数量为：{}",queueName,messageCount);
                //发送邮件
                try {
                    javaMailUtil.sendMailForQueue(queueName,messageCount);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }else {
                log.info("【监控模块】 {}队列中的消息，没有出现堆积问题！",queueName);
            }
        }
    }
}
